package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 检查手机号格式是否正确
        if (RegexUtils.isPhoneInvalid(phone)) {
            //如果不正确，返回错误信息
            return Result.fail("手机号码格式不正确");
        }
        // 如果正确
        // 生成验证码， 把验证码保存到Session中
        String code = RandomUtil.randomNumbers(6);
//        session.setAttribute("code",code)

        // 我们把生成的验证码保留到redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL,TimeUnit.MINUTES);
        // 进行验证码的发送
        log.info("{}", code);
        // 返回结果信息
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String code = loginForm.getCode();
        String phone = loginForm.getPhone();
        // 检验手机号是否符合格式
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("号码格式不正确");
        }
        // 如果符合格式
        // 验证码是否正确

        // 不正确返回错误信息
//        String cachecode = (String)session.getAttribute("code");
        String cachecode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        if (code == null || !code.equals(cachecode)) {
            return Result.fail("验证码信息错误");
        }

        // 正确 跟据号码 查询用户 如果存在，如果不存在 新建一个（快速注册） ，把用户信息放到Session中
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone, phone);
        User user = getOne(userLambdaQueryWrapper);

        if (user == null) {
            user = createUserWithPhone(phone);
        }


        // 为了防止显示敏感信息
       UserDTO userDTO=BeanUtil.copyProperties(user,UserDTO.class);

        //转换成map的形式
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));


        //        session.setAttribute("user",userDTO);
        // 保存到Redis中
        String token = UUID.randomUUID().toString();
        String tokenKey = LOGIN_USER_KEY + token;
        // 把token userMap 作为键值对放到了redis中
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        // 设置一个有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        // 返回token
        return Result.ok(token);
    }

    /**
     * 用户进行签到的功能
     * @return
     */
    @Override
    public Result sign() {
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String monthAndYear = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        String key = USER_SIGN_KEY + userId+monthAndYear;

        // 然后向redis中插入相关的数据
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }

    /**
     * 获得连续签到的次数
     * @return
     */
    @Override
    public Result signCount() {
        // 获取登录的用户
        Long userId = UserHolder.getUser().getId();

        // 获取系统中的当前的时间
        LocalDateTime now = LocalDateTime.now();
        String yearAndMonth = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY+userId+yearAndMonth;

        int dayOfMonth = now.getDayOfMonth();
        List<Long> resultList = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));

        if(resultList== null|| resultList.isEmpty()){
            return Result.ok(0);
        }
        Long number = resultList.get(0);
        if(number == 0 || number == null){
            return Result.ok(0);
        }


        // 执行计数的业务逻辑
        int count = 0;
        while(true){
            if((number&1)!=0){
                count ++;
            }else{
                break;
            }
            number>>=1;
        }
        return Result.ok(count);
    }

    public User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }


}
